const state = {
  menuList: [], // 菜单集合
  currentMenu: null // 当前选中菜单
}

const getters = {
  // 获取菜单集合
  getMenuList: state => {
    return state.menuList
  },
  getMenuOptions: state => {
    return state.menuList.map(menu => {
      return {
        value: menu.deviceCode,
        label: menu.deviceName
      };
    });
  }
}

const mutations = {
  // 初始化菜单集合
  setMenuList(state, menuList) {
    state.menuList = menuList
  },
  // 设置当前选中菜单
  setCurrentMenu(state, menu) {
    if (typeof menu === 'object') {
      state.currentMenu = menu
    } else {
      let currentMenu = findMenu(state.menuList, menu)
      if (currentMenu) {
        state.currentMenu = currentMenu
      }
    }
  }
}

function findMenu(list, url) {
  if (!list || list.length <= 0) {
    return null
  }
  let currentMenu = null
  for (let i=0; i<list.length; i++) {
    if (list[i].url === url) {
      currentMenu = list[i]
      break
    }
    currentMenu = findMenu(list[i].children, url)
    if (currentMenu) {
      break
    }
  }

  return currentMenu
}

export default {
  state,
  getters,
  mutations
}